package com.mall.shopping.services.product_goods_recommend;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.order.StockQueryService;
import com.mall.order.dto.StockQueryDto;
import com.mall.shopping.IProductService;
import com.mall.shopping.constant.GlobalConstants;
import com.mall.shopping.converter.PanelContent2ContentItemDtoConverter;
import com.mall.shopping.converter.PanelConverter;
import com.mall.shopping.converter.ProductConverter;
import com.mall.shopping.converter.ProductDetailConverter;
import com.mall.shopping.dal.entitys.*;
import com.mall.shopping.dal.persistence.ItemDescMapper;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @description:
 * @author 岳子昂
 * @date 2022-01-20 10:53
 * @version 1.0
 */
@Service // 这里要是dubbo包下的service
@Slf4j
public class IProductServiceImpl implements IProductService {

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    ItemDescMapper itemDescMapper;

    @Autowired
    PanelContentMapper panelContentMapper;

    @Autowired
    PanelMapper panelMapper;

    @Reference(timeout = 3000,retries = 2, check = false)
    StockQueryService stockQueryService;

    @Autowired
    ProductDetailConverter productDetailConverter;

    @Autowired
    ProductConverter productConverter;

    @Autowired
    PanelContent2ContentItemDtoConverter panelContent2ContentItemDtoConverter ;

    @Autowired
    PanelConverter panelConverter;


    /**
     * @description:
     * @param:
     * @return:
     * @author 岳子昂
     * @date: 2022-01-20 10:53
     */
    @Override
    public ProductDetailResponse getProductDetail(ProductDetailRequest request) {
        ProductDetailResponse response = new ProductDetailResponse();
        try {

            // 参数校验
            request.requestCheck();

            // 开始查询
            Long id = request.getId();
            Item item = itemMapper.selectByPrimaryKey(id);
            ItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(id);

            // 根据商品库存，设置limitNum
            StockQueryDto stockQueryDto = stockQueryService.stockQuery(id);
            Long limitNum = stockQueryDto.getLimitNum();
            item.setLimitNum(limitNum.intValue());

            // do转换为dto
            // 首先前六个成员变量
            ProductDetailDto productDetailDto = productDetailConverter.item2ProducrdetailDto(item);
            // 第七个成员变量，detail
            productDetailDto.setDetail(itemDesc.getItemDesc());
            // 第八个成员变量，imageSmall
            productDetailDto.setProductImageSmall(item.getImages());



            // 走到这里没有出错即为成功，为response封装成功数据
            response.setCode("000000");
            response.setMsg("成功");
            response.setProductDetailDto(productDetailDto);
        }catch (Exception e){
            e.printStackTrace();
            log.error("IProductServiceImpl.getProductDetail occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }

        return response;
    }

    /**
     * @description:
     * @param:
     * @return:
     * @author 岳子昂
     * @date: 2022-01-20 10:53
     */
    @Override
    public AllProductResponse getAllProduct(AllProductRequest request) {
        AllProductResponse response = new AllProductResponse();
        try {
            // 参数校验，确保page和size不为空
            request.requestCheck();

            //开始逻辑
            Integer page = request.getPage();
            Integer size = request.getSize();
            String sort = request.getSort();
            Integer priceGt = request.getPriceGt();
            Integer priceLte = request.getPriceLte();
            Long cid = request.getCid();

            // 开始分页插件
            PageHelper.startPage(page, size);

            List<Item> items = null;

            // 若所有附加条件都是空，那就把所有的都查出来
            if (cid == null && (sort == null || sort.equals("")) && priceGt == null && priceLte == null){
                items = itemMapper.selectAll();
            }else {
                // 有条件不是空，那么就按照条件往example里放值
                Example example = new Example(Item.class);
                Example.Criteria criteria = example.createCriteria();
                // 首次按判断cid 若cid == null，就查询全部，若不等于null，就查询某个类别的
                if (cid != null){
                    criteria.andEqualTo("cid",cid);
                }
                // 其次判断 sort， Sort = 1 默认值，Sort = -1 desc
                if (sort != null){
                    if (sort.equals("1")){
                        example.setOrderByClause("price");
                    }else if (sort.equals("-1")){
                        example.setOrderByClause("price desc");
                    }
                }
                // 判断最高价
                if (priceLte != null){
                    criteria.andLessThanOrEqualTo("price",priceLte);
                }
                // 判断最低价
                if (priceGt != null){
                    criteria.andGreaterThanOrEqualTo("price",priceGt);
                }

                // 将所有可能性都装入example之后，使用example查询
                items = itemMapper.selectByExample(example);
            }

            // item 转换 为productDto
            List<ProductDto> productDtos = productConverter.items2Dto(items);

            // 创建pageInfo对象，获取total
            PageInfo<Item> pageInfo = new PageInfo<>(items);
            long total = pageInfo.getTotal();

            // 创建allProduct对象
            AllProductDto allProductDto = new AllProductDto();
            allProductDto.setData(productDtos);
            allProductDto.setTotal(total);

            // 装入response
            response.setCode("000000");
            response.setMsg("成功");
            response.setAllProductDto(allProductDto);

        }catch (Exception e){
            log.error("IProductServiceImpl.getAllProduct occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    /**
     * @description:
     * @param:
     * @return:
     * @author 岳子昂
     * @date: 2022-01-20 10:53
     */
    @Override
    public RecommendResponse getRecommendGoods() {
        RecommendResponse response = new RecommendResponse();
        try {
            // 没有参数，所以不需要参数校验

            // 从panel-content表中查
            // 查出panelId等于GlobalConstants类中RECOMMEND_PANEL_ID的list
            int panelId = GlobalConstants.RECOMMEND_PANEL_ID;
            Example example = new Example(PanelContent.class);
            example.createCriteria().andEqualTo("panelId",panelId);
            List<PanelContent> panelContents = panelContentMapper.selectByExample(example);

            // panel-content转换成PanelContentItemDto
            List<PanelContentItemDto> itemDtos = panelContent2ContentItemDtoConverter.contents2itemDtos(panelContents);
            // 根据其中的productId，查出对应的product
            // 取出name，price，和subTitle，放入PanelContentItemDto中
            for (PanelContentItemDto item : itemDtos) {
                Long productId = item.getProductId();
                Item i = itemMapper.selectByPrimaryKey(productId);
                item.setProductName(i.getTitle());
                item.setSalePrice(i.getPrice());
                item.setSubTitle(i.getSellPoint());
            }

            // 根据panelId查找panel表
            Panel panel = panelMapper.selectByPrimaryKey(panelId);

            // panel转换为PanelDto
            PanelDto panelDto = panelConverter.panelDoToDto(panel);

            // PanelContentItemDto放入panelDto
            panelDto.setPanelContentItems(itemDtos);

            // 因为response对象中放的是set类型的对象，所以要将对象放到set中
            Set<PanelDto> panelDtos = new HashSet<>();
            panelDtos.add(panelDto);

            // 装入response
            response.setCode("000000");
            response.setMsg("成功");
            response.setPanelContentItemDtos(panelDtos);

        }catch (Exception e){
            log.error("IProductServiceImpl.getRecommendGoods occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }
}
